import { loginAPI, getProfileAPI, getUserInfoAPI } from '@/api'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    userInfo: {}
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
    // 持久存储本地token
    setToken(token)
  },
  // 删除token
  DEL_TOKEN: (state) => {
    state.token = ''
    // 删除本地token
    removeToken()
  },
  // 设置用户名
  SET_USER(state, value) {
    state.userInfo = value
  },
  // 删除用户信息
  REMOVE_USER(state) {
    state.userInfo = {}
  }
}

const actions = {
  // 登录
  async loginAction({ commit }, data) {
    const res = await loginAPI(data)
    // 本地cookie存储token（在当前模块不需要加模块名）
    commit('SET_TOKEN', res.data)
    return res
  },
  // 获取用户基本信息
  async getProfile({ commit }) {
    const { data: UserObj } = await getProfileAPI()
    const { data: PhotoObj } = await getUserInfoAPI(UserObj.userId)
    commit('SET_USER', { ...UserObj, ...PhotoObj })
  },
  // 退出登录清空token
  logoutAction({ commit }) {
    // 删除vuex里token和本地token
    commit('DEL_TOKEN')
    // 删除vuex里用户信息
    commit('REMOVE_USER')
    // 重置路由
    resetRouter()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
